package com.ruoyi.web.controller.asset;

import com.ruoyi.asset.domain.AssetClique;
import com.ruoyi.asset.domain.AssetDetail;
import com.ruoyi.asset.domain.AssetImg;
import com.ruoyi.asset.service.IAssetCliqueService;
import com.ruoyi.asset.service.IAssetDetailService;
import com.ruoyi.clique.domain.CliqueDetail;
import com.ruoyi.clique.service.ICliqueDetailService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 资产信息Controller
 * 
 * @author ruoyi
 * @date 2019-10-23
 */
@Controller
@RequestMapping("/asset/assetDetail")
public class AssetDetailController extends BaseController
{
    private String prefix = "asset";

    @Autowired
    private IAssetDetailService assetDetailService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ICliqueDetailService cliqueDetailService;
    @Autowired
    private IAssetCliqueService assetCliqueService;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private ISysDeptService sysDeptService;

    @RequiresPermissions("asset:assetDetail:view")
    @GetMapping()
    public String assetDetail()
    {
        return prefix + "/assetDetail";
    }

    /**
     * 查询资产信息列表
     */
    @RequiresPermissions("asset:assetDetail:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(AssetDetail assetDetail)
    {
        startPage();
        List<AssetDetail> list = assetDetailService.selectAssetDetailList(assetDetail);
        List<AssetDetail> imgCountList=assetDetailService.selectImgCountByAssetId();
        Map<Integer,Integer> imgCountMap=imgCountList.stream().collect(Collectors.toMap(AssetDetail::getId,AssetDetail::getImgCount));
        for (AssetDetail assetDetail1:list) {
            assetDetail1.setImgCount(imgCountMap.get(assetDetail1.getId()) != null ? imgCountMap.get(assetDetail1.getId()) : 0);
        }
        return getDataTable(list);
    }

    /**
     * 导出资产信息列表
     */
    @Log(title = "导出资产信息", businessType = BusinessType.EXPORT)
    @RequiresPermissions("asset:assetDetail:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(AssetDetail assetDetail)
    {
        List<AssetDetail> list = assetDetailService.selectAssetDetailList(assetDetail);
        for (AssetDetail ad:list) {
            if (StringUtils.isNotBlank(ad.getUseUser())){
                SysUser sysUser=userService.selectUserById(new Long(ad.getUseUser()));
                if (sysUser!=null){
                    ad.setUseUser(sysUser.getUserName());
                }
            }
            if (StringUtils.isNotBlank(ad.getManageUser())){
                SysUser sysUser=userService.selectUserById(new Long(ad.getManageUser()));
                if (sysUser!=null){
                    ad.setManageUser(sysUser.getUserName());
                }
            }
            if (StringUtils.isNotBlank(ad.getAssetType())){
                ad.setAssetType(dictDataService.selectDictLabel("asset_type",ad.getAssetType()));
            }
            if (StringUtils.isNotBlank(ad.getAssetUnit())){
                ad.setAssetUnit(dictDataService.selectDictLabel("unit_name",ad.getAssetUnit()));
            }
//            ad.setIdStr(ad.getIdStr());
        }
        ExcelUtil<AssetDetail> util = new ExcelUtil<AssetDetail>(AssetDetail.class);
        return util.exportExcel(list, "资产信息");
    }

    /**
     * 新增资产信息
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存资产信息
     */
    @RequiresPermissions("asset:assetDetail:add")
    @Log(title = "新增资产信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(AssetDetail assetDetail)
    {
        assetDetail.setCreateBy(ShiroUtils.getUserId().toString());
        return toAjax(assetDetailService.insertAssetDetail(assetDetail));
    }

    /**
     * 修改资产信息
     */
    @GetMapping("/edit/{param}")
    public String edit(@PathVariable("param") String param, ModelMap mmap)
    {
        String[] str=param.split(",");
        AssetDetail assetDetail = assetDetailService.selectAssetDetailById(str[0]);
        mmap.put("assetDetail", assetDetail);
        SysUser sysUser=new SysUser();
        if (StringUtils.isNotBlank(assetDetail.getManageDept())){
            sysUser.setDeptId(Long.parseLong(assetDetail.getManageDept()));
            mmap.put("manageUserList", userService.selectUserList(sysUser));
        }
        if (StringUtils.isNotBlank(assetDetail.getDeptId())){
            sysUser.setDeptId(Long.parseLong(assetDetail.getDeptId()));
            mmap.put("useUserList", userService.selectUserList(sysUser));
        }
        mmap.put("showFlag",Boolean.parseBoolean(str[1]));
        mmap.put("audioFlag",Boolean.parseBoolean(str[2]));
        mmap.put("editFlag",Boolean.parseBoolean(str[3]));
        return prefix + "/edit";
    }

    /**
     * 修改保存资产信息
     */
//    @RequiresPermissions("asset:assetDetail:add")
    @Log(title = "修改资产信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(AssetDetail assetDetail)
    {
        assetDetail.setUpdateBy(ShiroUtils.getUserId().toString());
        assetDetail.setUpdateTime(new Date());
        return toAjax(assetDetailService.updateAssetDetail(assetDetail));
    }

    /**
     * 删除资产信息
     */
    @RequiresPermissions("asset:assetDetail:remove")
    @Log(title = "删除资产信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(assetDetailService.deleteAssetDetailByIds(ids));
    }

    @RequiresPermissions("asset:assetDetail:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<AssetDetail> util = new ExcelUtil<AssetDetail>(AssetDetail.class);
        return util.importTemplateExcel("资产信息");
    }

    @Log(title = "导入资产信息", businessType = BusinessType.IMPORT)
    @RequiresPermissions("asset:assetDetail:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<AssetDetail> util = new ExcelUtil<AssetDetail>(AssetDetail.class);
        List<AssetDetail> userList = util.importExcel(file.getInputStream());
        String operName = ShiroUtils.getSysUser().getUserId().toString();
        String message = assetDetailService.importAssetDetail(userList, operName);
        return AjaxResult.success(message);
    }

    /**
     * 匹配集团信息
     */
    @GetMapping("/syncView/{id}")
    public String syncView(@PathVariable("id") String id, ModelMap mmap){
        mmap.put("assetSyncId",id);
        return prefix + "/syncView";
    }

    /**
     * 集团未匹配信息
     */
    @PostMapping("/syncList")
    @ResponseBody
    public TableDataInfo syncList(CliqueDetail cliqueDetail){
        startPage();
        cliqueDetail.setStatus("0");
        List<CliqueDetail> cliqueDetails=cliqueDetailService.selectCliqueDetailList(cliqueDetail);
        return getDataTable(cliqueDetails);
    }

    /**
     * 匹配集团信息
     */
    @Log(title = "匹配资产信息", businessType = BusinessType.UPDATE)
    @RequiresPermissions("asset:assetDetail:edit")
    @PostMapping("/sync")
    @ResponseBody
    public AjaxResult sync(AssetClique assetClique){
        assetCliqueService.insertAssetClique(assetClique);

        AssetDetail assetDetail=assetDetailService.selectAssetDetailById(assetClique.getAssetId()+"");
        assetDetail.setId(assetClique.getAssetId());
        assetDetail.setStatus("3");
        CliqueDetail cliqueDetailParam=cliqueDetailService.selectCliqueDetailById(new Long(assetClique.getCliqueId()));
        assetDetail.setAssetCode(cliqueDetailParam.getAssetCode());
        assetDetail.setAssetNo(cliqueDetailParam.getAssetNo());
        assetDetail.setUpdateBy(ShiroUtils.getUserId().toString());
        assetDetailService.updateAssetDetail(assetDetail);

        CliqueDetail cliqueDetail=new CliqueDetail();
        cliqueDetail.setId(assetClique.getCliqueId());
        cliqueDetail.setStatus("1");
        cliqueDetailService.updateCliqueDetail(cliqueDetail);

        return AjaxResult.success("关联成功");
    }

    /**
     * 打印资产信息
     */
    @GetMapping("/printView/{id}")
    public String printView(@PathVariable("id") String id, ModelMap mmap){
        AssetDetail assetDetail=assetDetailService.selectAssetDetailById(id);
        if (StringUtils.isNotBlank(assetDetail.getUseUser())){
            SysUser sysUser=userService.selectUserById(Long.parseLong(assetDetail.getUseUser()));
            assetDetail.setUseUser(sysUser.getUserName());
        }
        assetDetail.setUseStatus(dictDataService.selectDictLabel("use_status",assetDetail.getUseStatus()));
        mmap.put("assetDetail",assetDetail);
        SysDept sysDept=sysDeptService.selectDeptById(new Long(assetDetail.getDeptId()));
        SysDept sysDeptCompany=sysDeptService.selectDeptById(sysDept.getParentId());
        mmap.put("company",sysDeptCompany.getDeptName());
        mmap.put("qrCodeUrl", Global.getQrCodeUrl());
        return prefix + "/printView";
    }

    /**
     * 上传图片
     */
    @Log(title = "上资产图片", businessType = BusinessType.UPDATE)
    @PostMapping("/updateImgUrl")
    @ResponseBody
    public AjaxResult updateAvatar(@RequestParam(value = "file_data",required = false) MultipartFile files,@RequestParam(value = "id",required = false)String id)
    {
        try
        {
            if (files!=null){
                String path=FileUploadUtils.upload(Global.getUploadPath(), files);
                AssetImg assetImg=new AssetImg();
                assetImg.setCreateBy(ShiroUtils.getUserId()+"");
                assetImg.setAssetId(id);
                assetImg.setImgPath(path);
                assetDetailService.addImgSave(assetImg);

            }
            return AjaxResult.success("成功");
        } catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }
    /**
     * 展示资产图片
     */
    @GetMapping("/showImg/{id}")
    public String showImg(@PathVariable("id") String id, ModelMap mmap){
        List<String> imgList=assetDetailService.findImg(id.split(",")[0]);
        mmap.put("imgList",imgList);
        mmap.put("assetImgId",id.split(",")[0]);
        mmap.put("delFlag",Boolean.parseBoolean(id.split(",")[1]));
        return prefix + "/showImg";
    }

    /**
     * 删除图片
     */
    @PostMapping("/removeImg")
    @ResponseBody
    public AjaxResult removeImg(AssetImg assetImg){
        assetImg.setUpdateBy(ShiroUtils.getUserId()+"");
        return toAjax(assetDetailService.removeImg(assetImg));
    }

    /**
     * 添加资产图片
     */
    @GetMapping("/addImg/{id}")
    public String addImg(@PathVariable("id") String id, ModelMap mmap){
        mmap.put("assetId",id);
        return prefix + "/upload";
    }
//    /**
//     * 添加资产图片保存
//     */
//    @RequiresPermissions("asset:assetDetail:remove")
//    @Log(title = "资产信息", businessType = BusinessType.DELETE)
//    @PostMapping( "/addImgSave")
//    @ResponseBody
//    public AjaxResult addImgSave(@RequestParam(value = "id",required = false)String id,@RequestParam(value = "path",required = false)String path)
//    {
//        return toAjax(assetDetailService.addImgSave(id,path));
//    }

    /**
     * 展示匹配信息
     */
    @GetMapping("/showClique/{id}")
    public String showClique(@PathVariable("id") String id, ModelMap mmap){
        AssetDetail assetDetail=assetDetailService.selectAssetDetailById(id);
        AssetClique assetClique=assetCliqueService.selectAssetCliqueById(Long.parseLong(id));
        CliqueDetail cliqueDetail=cliqueDetailService.selectCliqueDetailById(new Long(assetClique.getCliqueId()));
        assetDetail.setAssetType(dictDataService.selectDictLabel("asset_type",assetDetail.getAssetType()));
        cliqueDetail.setAssetType(dictDataService.selectDictLabel("asset_type",cliqueDetail.getAssetType()));
        assetDetail.setUseStatus(dictDataService.selectDictLabel("use_status",assetDetail.getUseStatus()));
        mmap.put("assetDetail",assetDetail);
        mmap.put("cliqueDetail",cliqueDetail);
        return prefix + "/showClique";
    }

    /**
     * 遗失报废
     */
    @GetMapping("/lostScrap/{id}")
    public String lostScrap(@PathVariable("id") String id, ModelMap mmap){
        AssetDetail assetDetail=assetDetailService.selectAssetDetailById(id);
        mmap.put("amount",assetDetail.getAmount());
        mmap.put("assetId",id);
        return prefix + "/lostScrap";
    }
}
